package com.study.servlet.cookie.prac02;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.study.servlet.cookie.prac02.domain.Book;

public class ShowDetail extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8") ;
		PrintWriter out = response.getWriter() ;
		//1.要得到书的id，去找到这本书对象
		String id = request.getParameter("id") ;
		Book book = BookDB.getBookById(id) ;
		out.write("书的详情如下：" + book + "" +
				"&nbsp;&nbsp;&nbsp;&nbsp;" +
				"<a href='"+request.getContextPath()+"/servlet/ShowAllProducts'>返回</a>") ;
		String ids = generateIds(request, id) ;
		//写Cookie
		Cookie cookie = new Cookie("HistoryBooks", ids) ;
		cookie.setPath(request.getContextPath()) ;
		cookie.setMaxAge(Integer.MAX_VALUE) ;
		response.addCookie(cookie) ;
		out.close() ;
	}
	
	/**
	* @Name: generateIds
	* @Description: 拼接历史浏览记录ids字符串
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-3-1 下午10:25:15
	* @Parameters: @param request
	* @Parameters: @param id 当前查看的Book记录id
	* @Return: String 返回历史浏览记录ids字符串
	 */
	private String generateIds(HttpServletRequest request,String id){
		//获取Cookie
		Cookie c[] = request.getCookies();
		//如果Cookie为空，直接返回当前查看的Book记录id
		if(c==null || c.length==0){
			return id;
		}
		Cookie mycookie = null;
		//获取历史浏览记录Cookie
		for(int i=0;i<c.length;i++){
			Cookie currentCookie = c[i];
			if("HistoryBooks".equals(currentCookie.getName())){
				mycookie = currentCookie;
				break;
			}
		}
		//如果不存在，直接返回当前查看的Book记录id
		if(mycookie==null){
			return id;
		}
		//获取历史浏览记录Cookie的值：ids字符串
		String ids = mycookie.getValue();
		//获取id数组
		String idsarray[] = ids.split("-");
		//历史浏览记录，具备先进先出特点:所以用LinkedList
		LinkedList<String> list = new LinkedList<String>(Arrays.asList(idsarray));
		/**
		 * 分析：
		 * 	1、链表长度小于3
		 * 		如果链表中包含正在浏览的id值，则移动到表头
		 * 		如果不包含，直接添加到表头
		 * 	2、链表长度大于等于3
		 * 		如果链表中包含正在浏览的id值，则移动到表头
		 * 		如果不包含，移除链尾id元素，将长在浏览的id值放到表头
		 */
		if(list.size()<3){
			if(list.contains(id)){
				list.remove(id);
			}
		}else{
			if(list.contains(id)){
				list.remove(id);
			}else{
				list.removeLast();
			}
		}
		list.addFirst(id);
		//拼接ids字符串
		StringBuffer sb = new StringBuffer("");
		for(int i=0;i<list.size();i++){
			if(i>0)
				sb.append("-");
			sb.append(list.get(i));
		}
		return sb.toString();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
